const http = require('http');

module.exports = class Koa {
    constructor() {
        this.middlewares = [];
    }

    use(middleware) {
        this.middlewares.push(middleware);
    }

    handleRequest(ctx) {
        let index = -1;
        const next = async () => {
            index++;
            const middleware = this.middlewares[index];
            if (middleware) {
                await middleware(ctx, next);
            }
        };
        return next();
    }

    listen(port, callback) {
        const server = http.createServer((req, res) => {
            const ctx = { req, res };
            this.handleRequest(ctx).then(() => {
                res.end(ctx.body);
            });
        });
        server.listen(port, callback);
    }
}
